// pages/publish/publish.js
const Multipart = require('../../utils/Multipart.min');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:['--请选择合适地点--','梅苑','兰苑','菊苑','其他'],
    addressIndex:0,

    classify:['--请选择分类--','生活类','学习类','电器类','手机类','化妆品','其他'],
    classifyIndex:0,

    //编辑按钮新增字段
    goods_name:"",
    goods_note:"",
    goods_price:null,

    // 图片数组数据
    imageList:[],
    // 发布须知
    is_Check:false,

    isDisabled:false,
  },

  // 选择器发生改变的时候
  pickerAddress(e){
    // console.log(e.detail.value);
    this.setData({
      addressIndex:e.detail.value
    })
  },
  pickerClassify(e){
    this.setData({
      classifyIndex:e.detail.value
    })
  },

  // 展示提示卡片
  showTip(){
    wx.showModal({
      content: `
      1.本小程序仅提供闲置二手信息发布和展示功能，不涉及资金交易。
      2.建议在学校内当面进行交易，一手交钱一手交货。`,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#3cba92',
    });
  },
  goToKnow(){
    wx.navigateTo({
      url: '/pages/mustKnow/mustKnow',
    });
  },

  // 上传图片
  upImage(){
    const that = this;
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
       // console.log(tempFilePaths);
        that.setData({
          imageList:tempFilePaths
        })
      }
    })
  },
  // 生命周期函数
  onLoad: function (options) {
    console.log(options)
  },
  // 监听小程序显示
  onShow(){
    if(!wx.getStorageSync('isLogin')){
      wx.showModal({
        title: '提示',
        content: '请先进行授权登录',
        showCancel: false,
        confirmText: '跳转授权',
        confirmColor: '#3CC51F',
        success: (result) => {
          if (result.confirm) {
            wx.switchTab({
              url: '/pages/user/user',
            });
          }
        },
      });
        
    }

    const app = getApp();
    //监听编辑按钮传递的edit_goodsid
    if(app.globalData.edit_goodsid!==-1){
      //请求商品详情页数据
      const token = wx.getStorageSync('cookie');
      wx.request({
        url: `http://gzhu.a.vaiwan.com/getGoodsDetail/${app.globalData.edit_goodsid}?access_token=${token}`,

        method: "GET",
        success: (result) => {
          console.log("获取商品详情", result);
          this.setData({
            //imageList: result.data.data.goodsImgUrls.split(","),
            goods_name: result.data.data.goodsName,
            goods_note: result.data.data.goodsNote,
            goods_price: result.data.data.goodsPrice,
            addressIndex: (this.data.address || []).findIndex((item) => item === result.data.data.goodsAddress),
            classifyIndex: result.data.data.type
          });
          //获取完数据后重置全局变量edit_goodsid为-1
          //app.globalData.edit_goodsid = -1;
        },
      });
    }
  },

  // 表单提交
  formSubmit(e){
    if(this.data.is_Check){

      this.setData({
        isDisabled:true
      })

      console.log(e.detail.value);

      let shopInfo= e.detail.value;

      // shopInfo['userId'] = wx.getStorageSync('cookie');
      // console.log('cookie值',wx.getStorageSync('cookie'))

      const token = wx.getStorageSync('cookie');

      shopInfo.goodsPrice = shopInfo.goodsPrice-0;

      shopInfo.type = shopInfo.type-0;


      if(shopInfo.type===0){
        this.showModal('请选择分类！');
        this.setData({
          isDisabled:false
        })
        return;
      }
      
      // 图片文件·
      let files = this.data.imageList.map(filePath=>({
        name:'img',
        filePath:filePath
      }))

      // 其他字段
      let fields = Object.keys(shopInfo).map(key=>({
        name:key,
        value:shopInfo[key]
      }))
      var url=`http://gzhu.a.vaiwan.com/uploadGoods`;
      const app = getApp();
      const that=this;

      //如果edit_goosid!=-1，增加一个字段,并改变url
      if(app.globalData.edit_goodsid !== -1){
        fields.push({"name": "goodsId", "value": app.globalData.edit_goodsid});
        url=`http://gzhu.a.vaiwan.com/updateMygoods`;
      }
      console.log('files',files);//图片文件
      console.log('fields',fields);//其他字段
      new Multipart({
        files, //提交的文件
        fields, //提交的字段
      }).submit(url+`?access_token=${token}`)
      .then(res=>{
        console.log('成功了',res);
        if(res.data.code!==200){
          that.showModal(res.data.message);
          that.setData({
            isDisabled:false
          })
          return;
        }
        wx.showModal({
          title: '提示',
          content: '发布成功,可到【我的发布】中查看已发布的商品。',
          showCancel: false,
          confirmText: '知道了',
          confirmColor: '#3CC51F',
          success(){
            wx.redirectTo({
              url: '/pages/myPublish/myPublish',
            });
            //重置app.globalData.edit_goodsid为 -1，还原新增字段为空
            app.globalData.edit_goodsid = -1;
            that.setData({
              goods_name:"",
              goods_note:"",
              goods_price:null,
              classifyIndex:0,
              addressIndex:0
            })
          }
        });
      }).catch(err=>{
        console.log('失败了',err)
      })

    }else{
      wx.showModal({
        title: '提示',
        content: '请勾选《发布须知》',
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#3CC51F',
      });
    }
  },

  // 发布须知是否已经勾选
  isChecked(){
    let flag = this.data.is_Check
    this.setData({
      is_Check:!flag
    })
  },

  //监听编辑商品信息未完成发布就切换页面的情况

  // 这是生命周期函数
  onHide(){
    const app = getApp();
    const that=this;
   // console.log(app.globalData.edit_goodsid);
    if(app.globalData.edit_goodsid !==-1){
      wx.showModal({
        title: '提示',
        content: '是否退出此次编辑？',
        confirmText: "确定退出",
        confirmColor: '#3CC51F',
        success (res) {
          if (res.confirm) {
            //给全局变量重置为-1
            app.globalData.edit_goodsid =-1;
            //console.log(app.globalData.edit_goodsid);
            // 重置其他新增变量
            that.setData({
              goods_name:"",
              goods_note:"",
              goods_price:null,
              classifyIndex:0,
              addressIndex:0
            })
          }else if (res.cancel) {
          }
        }
      });
    }
  },


    // 展示弹框
    showModal(content,url){
      wx.showModal({
        title:'提示',
        content,
        showCancel: false,
        confirmText: '知道了',
        confirmColor: '#3CC51F',
        success: () => {
          if(url){
            wx.redirectTo({
              url,
            });
          }
        },
      });
    }

})